import React from 'react';
import request from '@/utils/request';
import { Empty } from 'antd';

import RecordCard from '../RecordCardEstimate/RecordCard';
import styles from './index.less';

const EstimateRec = ({ location, activeKey, refreshComp }) => {
    const { query } = location;
    const { id } = query;

    const [recordData, setRecordData] = React.useState([]);

    const [recordInfo, setRecordInfo] = React.useState('');

    // 获取估算记录人员的头像
    const getUserListImg = async employeeCodeList => {
        const result = await request('/api/uc/org/employee/v1/avatar/list', {
            method: 'POST',
            data: employeeCodeList
        });
        if (result.code === 10000) {
            return result.data;
        }
        return [];
    };

    // 由于数据结构问题reEstimationDetails 在这里获取详情页里得所有员工id去请求头像
    const getEmployeeCodes = result => {
        const ids = [];
        result.data.map(item => {
            if (item.reEstimationDetails) {
                item.reEstimationDetails.map(v => {
                    ids.push(v.employeeCode);
                    return '';
                });
            }
            ids.push(item.employeeCode);
            return '';
        });
        // id去重
        const unique = arr => Array.from(new Set(arr));
        return unique(ids);
    };
    // 写入头像数据进行值的赋值
    const setAvatarFiles = (result, avatarData = []) =>
        result.data.map(i => {
            const matchData = avatarData.find(v => i.employeeCode === v.employeeCode);
            let resultItem = i;
            if (matchData) {
                resultItem = {
                    ...resultItem,
                    avatarFile: matchData.avatarFile
                };
            }
            if (i.reEstimationDetails) {
                const list = i.reEstimationDetails.map(r => {
                    const detailData = avatarData.find(v => r.employeeCode === v.employeeCode);
                    return {
                        ...r,
                        avatarFile: detailData.avatarFile
                    };
                });
                resultItem = {
                    ...resultItem,
                    reEstimationDetails: list
                };
            }
            return resultItem;
        });

    // 获取估算记录数据
    const getEstimateRecordList = async () => {
        const result = await request('/api/oa/v1/work/task/estimation/gettaskestimationlist', {
            method: 'POST',
            data: {
                taskId: id
            }
        });
        if (result.code !== 10000) return;
        const avatarData = await getUserListImg(getEmployeeCodes(result));
        if (Array.isArray(avatarData)) {
            setRecordData(setAvatarFiles(result, avatarData));
        } else {
            setRecordData(result.data);
        }
    };
    // 获取工作量数据
    const getRecordInfo = async () => {
        const result = await request(`/api/oa/v1/work/task/estimation/gettaskestimationsituation/${id}`, {
            method: 'GET'
        });
        if (result.code === 10000) {
            setRecordInfo(result.data);
        }
    };

    React.useEffect(() => {
        if (activeKey === 'assessmentRec') {
            getEstimateRecordList();
            getRecordInfo();
        }
    }, [activeKey, refreshComp]);

    const getResultNode = result => (
        <>
            <div>
                工作量：
                <span className={styles.score}>{result}</span>
            </div>
        </>
    );

    const getEstimationValue = record => {
        let value = record.estimationValue;
        if (record && record.reEstimationDetails.length > 0) {
            const { reEstimationDetails } = record;
            [...reEstimationDetails].reverse().some(item => {
                if (item.estimationValue) {
                    value = item.estimationValue;
                    return true;
                }
                return false;
            });
        }
        return value;
    };
    return (
        <>
            <div className={styles.summary}>
                <span>
                    估算人数：<span className={styles.number}>{recordInfo.estimateTotalNum || 0}人</span>（待估：
                    {recordInfo.waitingEstimateNum || 0}人，已估{recordInfo.estimatedNum || 0}人）
                </span>
                <span>
                    平均工作量：
                    <span className={styles.number}>{recordInfo.averageWorkloadValue || 0}</span>
                </span>
            </div>
            {recordData.length > 0 ? (
                <div className={styles.scoreContent}>
                    {recordData.map(record => (
                        <RecordCard
                            record={record}
                            key={record?.employeeCode}
                            result={getResultNode(getEstimationValue(record))}
                        />
                    ))}
                </div>
            ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
        </>
    );
};

export default EstimateRec;
